package com.otaku.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 标题：DemoInterceptor<br>
 * 功能说明：演示拦截器<br>
 * 系统版本：v1.0<br>
 * 开发人员： ganxiang20970 <br>
 * 开发时间：2018年04月19日 08:46<br>
 */
public class DemoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //请求处理前执行
        //可以在请求转发到对应控制器前添加参数
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //请求处理之后执行
        long startTime = (Long) request.getAttribute("startTime");
        request.removeAttribute("startTime");
        long endTime   = System.currentTimeMillis();
        request.setAttribute("handlingTime", endTime - startTime);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //请求完成后执行
    }
}
